package com.heima.comment.service.Impl;

import com.heima.aliyun.GreeTextScan;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.comment.vos.ApCommentVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {


    @Autowired
    GreeTextScan greeTextScan;

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    CommentHotService commentHotService;


    /**
     * 根据文章id查询评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //伪分页
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            dto.setSize(10);
        }
        dto.setSize(Math.min(dto.getSize(), 50));

        List<ApComment> commentList = null;

        if (dto.getIndex().intValue() == 1) {

            //查询热点评论
            commentList = mongoTemplate.find(Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0)
                            .and("flag").is(1))
                            .with(Sort.by(Sort.Order.desc("likes")))

                    , ApComment.class);


            //普通评论
            List<ApComment> apComments = mongoTemplate.find(Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0)
                            .and("flag").is(0)
                            .and("createdTime").lt(dto.getMinDate()))
                            .limit(dto.getSize() - commentList.size())
                            .with(Sort.by(Sort.Order.desc("createdTime")))
                    , ApComment.class);

            //合并评论
            commentList.addAll(apComments);


        } else {
            //查询所有的评论列表
            commentList = mongoTemplate.find(Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0)
                            .and("flag").is(0)
                            .and("createdTime").lt(dto.getMinDate()))
                            .limit(dto.getSize())
                            .with(Sort.by(Sort.Order.desc("createdTime")))
                    , ApComment.class);
        }


        //判断是否登录，若未登录则直接返回评论列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(commentList);
        }

        //若用户登录，则要返回点赞列表
        List<ApCommentVo> apCommentVoList = new ArrayList<>();

        //获取文章对应的所有评论列表id
        List<String> idList = commentList.stream().map(comment -> comment.getId()).collect(Collectors.toList());

        List<ApCommentLike> apCommentLikes = mongoTemplate.find(Query.query(Criteria
                        .where("commentId").in(idList)
                        .and("authorId").is(user.getId())
                        .and("operation").is(0))
                , ApCommentLike.class);

        //遍历当前用户点赞列表 评论列表
        if (commentList != null && commentList.size() > 0 && apCommentLikes != null && apCommentLikes.size() > 0) {
            //forEach 遍历
            commentList.forEach(comment -> {//遍历所有文章列表id
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(comment, apCommentVo);

                //遍历当前用户点赞列表
                apCommentLikes.forEach(commenLikes -> {
                    if (comment.getId().equals(commenLikes.getCommentId())) {
                        apCommentVo.setOperation((short) 0);
                    }
                });
                apCommentVoList.add(apCommentVo);
            });
            return ResponseResult.okResult(apCommentVoList);
        }

        return ResponseResult.okResult(commentList);
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取当前登录人
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 查询APUser用户信息
        Integer id = user.getId();
        ApUser apUser = userFeign.findUserById(id.longValue());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "非法用户");
        }

        //查询评论
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "暂无评论");
        }

        //判断用户是否重复点赞
        Query query = Query.query(Criteria
                .where("commentId").is(dto.getCommentId())
                .and("authorId").is(user.getId())
        );

        ApCommentLike commentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        if (commentLike != null && dto.getOperation() == 0 && commentLike.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "重复点赞");
        }

        //保存点赞
        if (dto.getOperation().intValue() == 0) {
            if (commentLike == null) {
                commentLike = new ApCommentLike();
                commentLike.setAuthorId(user.getId());
                commentLike.setCommentId(dto.getCommentId());

            }
            commentLike.setOperation(dto.getOperation());
            mongoTemplate.save(commentLike);

            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            //  计算热点评论  异步调用
            if (apComment.getLikes() >= 5 && apComment.getFlag().shortValue() == 0) {
                // 异步计算热点评论  多线程异步计算
                commentHotService.hotCommentExecutor(apComment.getEntryId(), apComment);
            }


        } else {//取消点赞
            commentLike.setOperation((short) 0);
            mongoTemplate.save(commentLike);

            apComment.setLikes((apComment.getLikes() + 1) < 0 ? 0 : apComment.getLikes() + 1);
            mongoTemplate.save(commentLike);
        }

        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }

        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //过滤垃圾内容
        //4.2 阿里云-文本内容审核
        //解析文本内容

//        List<Map> contentList = JSON.parseArray(dto.getContent(), Map.class);
//        String contents = contentList.stream()
//                .map(y -> y.get("content").toString())
//                .collect(Collectors.joining());
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("content", contents);
//        try {
//            Map maps = greeTextScan.greeTextScan(dto.getContent());
//
//            if (maps.get("suggestion").equals("block")) {
//                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容违规");
//            }
//            if (maps.get("suggestion").equals("review")) {
//                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容疑似违规");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("评论审核失败 id:{}", user.getId());
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容审核失败");
//        }

        //保存评论
        ApUser apUser = userFeign.findUserById(user.getId().longValue());

        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "非法用户");
        }

        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setCreatedTime(new Date());
        apComment.setEntryId(dto.getArticleId());
        apComment.setImage(apUser.getImage());
        apComment.setUpdatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);

        mongoTemplate.save(apComment);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
